import 'dart:io';
import 'package:fish_redux/fish_redux.dart';
import 'package:worker_manager/worker_manager.dart';
import 'action.dart';
import 'state.dart';

Cancelable<String> cancelable;

Effect<ItemComponentState> buildEffect() {
  return combineEffects(<Object, Effect<ItemComponentState>>{
    ItemComponentAction.action: _onAction,
    ItemComponentAction.onItemClick:_onItemClick,
    Lifecycle.dispose:_ondispose
  });
}

void _onAction(Action action, Context<ItemComponentState> ctx) {
}

void _ondispose(Action action, Context<ItemComponentState> ctx) {
  print('_ondispose()');
}

void _onItemClick(Action action, Context<ItemComponentState> ctx) {
  int index = action.payload;
  if(index == 0) {
    print('开启线程1');
    Executor().execute(arg1: 10,arg2: 20, fun2: test1);
    print('开启线程2');
    cancelable = Executor().execute(arg1: 10,fun1: test);
    cancelable.next(onNext: (v) {
      print('Executor():' + v.toString());
    }, onError: (){
      print('onError():');
    }
    );
    // cancelable.then((value){
    //   print('then():' + value.toString());
    // });
    // cancelable.onError((error, stackTrace) {
    //   print('onError():'+error.toString());
    // });
  }else if(index == 1){
    print('index == 1');
    cancelable.cancel();
  }else if(index == 2){
    print('_onItemClick:'+action.payload.toString());
    ctx.dispatch(ItemComponentActionCreator.refreshTitle());
  }

}

String test(int n){
  for(int i = n;i > 0;i --){
    sleep(Duration(seconds: 1));
    print('test():$i');
  }
  // String testStr = test1(0,0);
  // cancelable.asStream();
  // Future.value(testStr);
  return 'test';
}

String test1(int n,int i){
  for(int i = n;i > 0;i --){
    sleep(Duration(seconds: 1));
    print('test1():$i');
  }
  return 'test1';
}


int fib(int n,int i) {
  n-=1;
  print('fib():$n');
  return fib(n,i);
}